#include "CLineEdit.h"
#include "EventHelper.h"

#include <QApplication>
#include <QEvent>
#include <QKeyEvent>

CLineEdit::CLineEdit(QWidget *parent) : QLineEdit(parent) {
}

CLineEdit::CLineEdit(const QString &text, QWidget *parent) : QLineEdit(text, parent) {
}

void CLineEdit::setText(QString text) {
    QLineEdit::setText(text);
    setCursorPosition(0);
}

bool CLineEdit::event(QEvent *event) {
    if (Ev::keyIsDown(event)) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        int key = keyEvent->key();
        if ((key == Qt::Key_Return || key == Qt::Key_Enter)) {
            editFinish();
            return true;
        }
    }
    return QLineEdit::event(event);
}

void CLineEdit::focusOutEvent(QFocusEvent *event) {
    QLineEdit::focusOutEvent(event);
    emit loseFocus();
    editFinish();
}

void CLineEdit::editFinish() {
    if (hasFocus()) {
        clearFocus();
    }
    emit editFinished();
}
